import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';

class MusicPlayerWidget extends StatefulWidget {
  AudioPlayer musicController;
  var play;
  MusicPlayerWidget(AudioPlayer musicController, this.play): this.musicController = musicController;

  @override
  MusicPlayerWidgetState createState() => MusicPlayerWidgetState();
}


class MusicPlayerWidgetState extends State<MusicPlayerWidget> {
  AudioPlayer audioPlayer;

  PlayerState audioPlayerState = PlayerState.stopped;
  Duration duration = Duration();
  Duration position = Duration();


  @override
  void initState() {
    super.initState();
    audioPlayer = widget.musicController;
    audioPlayer.onDurationChanged.listen((Duration d) {
      setState(() {
        duration = d;
      });
    });

    audioPlayer.onPositionChanged.listen((Duration p) {
      setState(() {
        position = p;
      });
    });

    audioPlayer.onPlayerStateChanged.listen((PlayerState s) {
      setState(() {
        audioPlayerState = s;
      });
    });

    play();
  }

  @override
  void dispose() {
    super.dispose();
    audioPlayer.dispose();
  }

  void play() async {
    await widget.play();
    // await audioPlayer.play();
  }

  void pause() async {
    await audioPlayer.pause();
  }

  void seek(Duration duration) {
    audioPlayer.seek(duration);
  }

  String formatDuration(Duration d) {
    return d.toString().split('.').first;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(
              icon: audioPlayerState == PlayerState.playing ? Icon(Icons.pause) : Icon(Icons.play_arrow),
              onPressed: audioPlayer.state == PlayerState.stopped ? null : () {
                if (audioPlayerState == PlayerState.playing) {
                  pause();
                } else {
                  play();
                }
              },
            ),
          ],
        ),
        SizedBox(height: 16.0),
        Slider(
          value: position.inSeconds.toDouble(),
          min: 0.0,
          max: duration.inSeconds.toDouble(),
          onChanged: (double value) {
            seek(Duration(seconds: value.toInt()));
          },
        ),
        SizedBox(height: 16.0),
        Text(formatDuration(position) + ' / ' + formatDuration(duration)),
      ],
    );
  }
}
